﻿using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class ParticleShaderAdjustColor : MonoBehaviour
{
	private static MaterialPropertyBlock mpb = null;
	private static int colorNameId = -1;
	private static int colorStrengthNameId = -1;

	public Color color = Color.white;

	public float colorStrength = 1.0f;

	public bool updateColorOnce = false;

	private Renderer _renderer;

	#if UNITY_EDITOR
	void Reset()
	{
		if (_renderer == null)
		{
			_renderer = GetComponent<Renderer> ();
		}

		if (mpb == null)
		{
			colorNameId = Shader.PropertyToID ("_TintColor");
			colorStrengthNameId = Shader.PropertyToID("_ColorStrength");
			mpb = new MaterialPropertyBlock ();
		}

		color = _renderer.sharedMaterial.GetColor (colorNameId);
		if (_renderer.sharedMaterial.HasProperty (colorStrengthNameId))
		{
			colorStrength = _renderer.sharedMaterial.GetFloat (colorStrengthNameId);
		}
	}
	#endif

	#if !UNITY_EDITOR
	void Start()
	{
		if (_renderer == null)
		{
			_renderer = GetComponent<Renderer> ();
		}

		if (mpb == null)
		{
			colorNameId = Shader.PropertyToID ("_TintColor");
			colorStrengthNameId = Shader.PropertyToID("_ColorStrength");
			mpb = new MaterialPropertyBlock ();
		}
	}
	#endif

	void Update()
	{
		#if UNITY_EDITOR
		if (_renderer == null)
		{
			_renderer = GetComponent<Renderer> ();
		}

		if (mpb == null)
		{
			colorNameId = Shader.PropertyToID ("_TintColor");
			colorStrengthNameId = Shader.PropertyToID("_ColorStrength");
			mpb = new MaterialPropertyBlock ();
		}
		#endif

		if (_renderer != null && mpb != null)
		{
			_renderer.GetPropertyBlock(mpb);
			mpb.SetVector (colorNameId, color);
			mpb.SetFloat(colorStrengthNameId, colorStrength);
			_renderer.SetPropertyBlock (mpb);
		}

#if !UNITY_EDITOR
		if (updateColorOnce)
		{
			this.enabled = false;
		}
#endif
	}
}
